import 'dart:io';
import 'package:flutter/material.dart' as mat;

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import '../../core/network/internet_cubit.dart';
import '../../dialogs/soon_dialog.dart';
import 'logger_interceptor.dart';


bool get isDesktop {
  if (kIsWeb) return false;
  return [
    TargetPlatform.windows,
    TargetPlatform.linux,
    TargetPlatform.macOS,
  ].contains(defaultTargetPlatform);
}

class DioHelper {
  static Dio? dio;
/*
          'app_name': AppConstant.appName,
          'package_name': AppConstant.packageName,
          'version': AppConstant.version,
          'build_number': AppConstant.buildNumber,*/
  static init() {
    dio = Dio(
      BaseOptions(
        followRedirects: false,
        validateStatus: (status) => true,
        baseUrl: AppConstant.api,//isDesktop?AppConstant.locale:
        receiveDataWhenStatusError: true,
        headers: {
          'Content-Type': 'application/json',
        },
      ),
    )..interceptors.addAll(
        [
          LoggerInterceptor(),
        ],
      );
  }

  static Future<Response> getData({
    required String url,
    Map<String, dynamic>? query,
    String? bearerToken,
  }) async {
      dio?.options.headers = {
        if (bearerToken != null && bearerToken != '')
          'Authorization': 'Bearer $bearerToken',
      };

    var response = await dio!.get(
      url,
      queryParameters: query,
    );

    if(!kIsWeb && !Platform.isWindows) {
      checkLink(response);
    }
    return response;
  }

  static Future<Response> download({
    required String url,
    required String path,
    String? bearerToken,
    Map<String, dynamic>? query,
  }) async {
    dio?.options.headers = {
      if (bearerToken != null) 'Authorization': 'Bearer $bearerToken',
    };
    var response = await dio!.download(
      url,
      path,
      queryParameters: query,
    );
    if(!kIsWeb && !Platform.isWindows) {
      checkLink(response);
    }    return response;
  }

  static Future<Response?> postData({
    required String url,
    Map<String, dynamic>? query,
    dynamic data,
    String? bearerToken,
  }) async {
    if(InternetCubit.get(NavigatorService.navigatorKey.currentState!.overlay!.context).state == InternetState.disconnected){
    print(InternetCubit.get(NavigatorService.navigatorKey.currentState!.overlay!.context).state);
      showErrorMessage(message: 'عذراً هذه الميزة غير متوفرة بعد في وضع عدم الاتصال الرجاء إعادة المحاولة عند عودة الاتصال بالانترنت.');
      return null;
    }

    dio?.options.headers = {
      if (bearerToken != null) 'Authorization': 'Bearer $bearerToken',
    };
    try {
      var response = await dio!.post(
        url,
        queryParameters: query,
        data: FormData.fromMap(data),
      );
      if(!kIsWeb && !Platform.isWindows) {
        checkLink(response);
      }      return response;
    } catch (e) {
      print(e);
      showErrorMessage(message: 'حدث خطأ ما,الرجاء إعادة المحاولة!');
      return null;
    }
  }

  static Future<Response> patchData({
    required String url,
    Map<String, dynamic>? query,
    dynamic data,
    String? bearerToken,
  }) async {
    dio?.options.headers = {
      if (bearerToken != null) 'Authorization': 'Bearer $bearerToken',
    };
    return await dio!.patch(
      url,
      queryParameters: query,
      data: data,
    );
  }

  static Future<Response> deleteData({
    required String url,
    Map<String, dynamic>? query,
    dynamic data,
    String? bearerToken,
  }) async {
    dio?.options.headers = {
      if (bearerToken != null) 'Authorization': 'Bearer $bearerToken',
    };
    return await dio!.delete(
      url,
      queryParameters: query,
      data: data,
    );
  }

  static Future<Response> putData({
    required String url,
    Map<String, dynamic>? query,
    dynamic data,
    String? bearerToken,
  }) async {
    dio?.options.headers = {
      if (bearerToken != null) 'Authorization': 'Bearer $bearerToken',
    };
    return await dio!.put(
      url,
      queryParameters: query,
      data: data,
    );
  }

/*  static Future<Response?> download({
    required String url,
    Map<String, dynamic>? query,
    dynamic data,
    required File file,
    String ? bearerToken,
  }) async {
    dio?.options.headers = {
      if(bearerToken != null)
        'Authorization':'Bearer $bearerToken',
    };
    return await dio?.download(
      url,
      file,
      onReceiveProgress: (received,total) {

        int progress = (((received / total) * 100).toInt());

        print(progress);

        final url = file.path;

        //OpenFile.open(url);


      },
      queryParameters: query,
      data: data,

    );
  }*/
}
bool checkVersion(String v1, String v2){

  int f= int.parse(v1.replaceAll('.', ''));
  int s= int.parse(v2.replaceAll('.', ''));

  return f>s;
}
void checkLink(Response response) {
  if (response.data is! Map || kIsWeb) {
    return;
  }
  String? latestVersion = response.headers['latest-version']?[0];
  String? appLink = response.headers['app-link']?[0];
  if (!kIsWeb && checkVersion(latestVersion??"-1" , AppConstant.version)) {
    showUpdateDialog(appLink ?? '');
  }
  if (kDebugMode) {
    print(
        "Latest Version :$latestVersion , Current Version :${AppConstant.version}");
  }


}
